package cn.chenxiejia;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @version : V1.0
 * @program: maven
 * @ClassName: T6
 * @Description:
 * @Author: chenxiejia
 * @Date: 2022/2/7 20:53
 */
public class T6 {
    static volatile boolean stop = true;
    //原子类用于计数
    volatile AtomicInteger num = new AtomicInteger(50);
    //true 开启公平锁
    ReentrantLock lock = new ReentrantLock(true);

    public static void main(String[] args) {
        T6 t = new T6();
        while (stop) {
            for (int i = 1; i < 8; i++) {
                new Thread(t::min, "T" + i).start();
            }
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    void min() {
        //synchronized (this) {
        if (num.get() > 0) {
            //加锁
            //lock.lock();
            num.decrementAndGet();
            System.out.printf("%s卖出了一票，剩余%d票%n", Thread.currentThread().getName(), num.get());
            //解锁
            //lock.unlock();
        } else {
            stop = false;
        }
        //}
    }
}



